var facebook = {};

facebook.fbAppData = {
	appId : '266649356803428',
	permissions : 'user_events,friends_events'
};

facebook.graphUrl = 'https://graph.facebook.com/me/';
facebook.restUrl = 'https://api.facebook.com/method/';

facebook.fbUserData = {
	uid : '',
	accessToken : '',
	signedRequest : ''
};

facebook.resetUserData = function(){
	facebook.fbUserData = {
		uid : '',
		accessToken : '',
		signedRequest : ''
	};
}

facebook.getImageUrl = function(uid){
	var imageUrl = 'http://static.ak.fbcdn.net/rsrc.php/v2/yo/r/UlIqmHJn-SK.gif';
	if(uid){
		imageUrl = "http://graph.facebook.com/{0}/picture".format(uid);
	}
	return imageUrl;
}

window.fbAsyncInit = function () {
	FB.init({
		appId : facebook.fbAppData.appId,
		status : true,
		cookie : true,
		oauth : true,
		xfbml : true
	});
	
	FB.Event.subscribe('auth.logout',
		function(response) {
			facebook.resetUserData();
			getLoginStatus();
		}
	);
	
	FB.Event.subscribe('auth.login',
		function(response) {
			getLoginStatus();
		}
	);
	
	getLoginStatus();
};

(function (d) {
	var js,
	id = 'facebook-jssdk',
	ref = d.getElementsByTagName('script')[0];
	if (d.getElementById(id)) {
		return;
	}
	js = d.createElement('script');
	js.id = id;
	js.async = true;
	js.src = "https://connect.facebook.net/en_US/all.js";
	ref.parentNode.insertBefore(js, ref);
}(document));

var getLoginStatus = function () {
	FB.getLoginStatus(function (response) {
		if (response.status === 'connected') {
			facebook.resetUserData();
			facebook.fbUserData.uid = response.authResponse.userID;
			facebook.fbUserData.accessToken = response.authResponse.accessToken;
			facebook.fbUserData.signedRequest = response.authResponse.signedRequest;
			getUserData();
		} else if (response.status === 'not_authorized' || response.status === 'unknown') {
			$(window).trigger('fbnotloaded');
			doLogin();
		}
	});
}

var doLogin = function(){
	 FB.login(function(response) {
		if (response.status === 'connected') {
			getLoginStatus();
		} else {
			$(window).trigger('fbnotloaded');
		}
	 }, {scope: facebook.fbAppData.permissions });
}

var getUserData = function () {
	FB.api('/me', function (response) {
		$.extend(facebook.fbUserData, response);
		$(window).trigger('fbloaded');
	});
}